// $Id: main.cpp 2 2009-09-02 08:47:42Z joseph2002 $
/*
 * Copyright 2009 Joseph Wu
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
 *
 * For more information, see http://xpcomplus.sourceforge.net
 */

#include <iostream>
#include <xpcom/xpcom.hpp>
#include "IHelloWorld.hpp"
#include "nsIComponentRegistrar.hpp"
#include "nsIDirectoryServiceProvider.hpp"
#include "nsIFile.hpp"

void load_module(const char* module_name)
{
    using namespace xpcom;

    string module = module_name;
#ifdef XPCOM_PLATFORM_WIN32
    module += ".dll";
#else
    module = "lib" + module + ".so";
#endif

    ref_ptr<nsIDirectoryServiceProvider> dirsvc =
            services["@mozilla.org/file/directory_service;1"];

    bool persist;
    nsIFile_ptr module_file = dirsvc->getFile("XCurProcD", persist);
    module_file->appendNative(module);
    std::cout << "loading module: " << module_file->getNativePath() << std::endl;

    nsIComponentRegistrar_ptr registrar = library::component_registrar();
    registrar->autoRegister(module_file);
}

int main()
{
    using namespace xpcom;
    using namespace xpcom::example;

    try {
        // Init library
        library lib;

        // Auto-register hello module
        load_module("hello");

        // Make HelloWorld instance
        ref_ptr<IHelloWorld> p = components["@xpcomplus.sf.net/example-hello;1"];

        string result = p->sayHello(0);
        std::cout << result << std::endl;

        result = p->sayHello("My World");
        std::cout << result << std::endl;

    } catch (const xpcom::exception& e) {
        std::cerr << "caught xpcom::exception: " << e.code() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "caught std::exception: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "caught undefined exception" << std::endl;
    }
}
